var webServiceurl = "http://localhost/";

document.onreadystatechange = function()
{    
    if(document.readyState=="complete")
    {
        System.Gadget.settingsUI = "Settings.htm";
        System.Gadget.onSettingsClosed = settingsClosed;
        //System.Gadget.onUndock = resizeGadget;
        //System.Gadget.onDock = resizeGadget;         
        updateReadings();
        window.setInterval(function () {
                updateReadings();
            }, 15000);
    }        
}


function getReading(fname, elementid) {

    var e = document.getElementById(elementid);
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {

        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                var v = xhr.responseText;
                e.innerText = v.replace(/\"/g, '');
            }
            else {
                e.innerText = "Err:" + (new Date()).getSeconds();
            }
        }
    };

    try
    {
      var url = webServiceUrl + "EnergyMonWs.svc/json/" + fname + "?" + Math.random();
      xhr.open("GET", url, true);
      xhr.send(); 
    }
    catch(err)
    {
      // do nothing
    }

}


function updateReadings() 
{
    loadSettings();
    getReading("temp", "tempval");
    getReading("energy", "energyval");
    getReading("time", "timeval"); 
              
}

function settingsClosed(event)
{
    if(event.closeAction == event.Action.commit)
    {   
        updateReadings();
    }
}

function loadSettings()
{
    webServiceUrl = System.Gadget.Settings.read("webServiceUrl");
}
